<template>
    <div class="home-left">
        <div v-for="father in routerList">
            <div class="father-item" v-if="father.children.length > 0" @click="openTheFather(father)">{{father.pagename}}</div>
            <div class="father-item" v-else @click="openPahe(father.path)">{{father.pagename}}</div>
            <div v-if="father.showChild" v-for="child in father.children">
                <div class="child-item" @click="openTheChild(child)">{{child.pagename}}</div>
            </div>
        </div>
    </div>
    <div class="home-right">
        <router-view></router-view>
    </div>
</template>

<script setup>
import { getPages } from './api/page'
const router = useRouter()
let pageList = ref([])
let routerList = ref([])

const initPageList = ()=>{
  getPages().then(res=>{
    pageList.value = res.data.list
    initRouter(res.data.list)
  })
}
const init = ()=> {
  initPageList()
}

// 打开页面
const openPahe = (path) => {
    router.push(path)
}

const getPageByFatherId = (fatherid, list) => {
    return list.filter(item => item.fatherid === fatherid)
}

const sortListByIndex = (list) => {
    return list.sort((a, b) => a.index - b.index)
}

const initRouter = (list)=>{
    let fatherList = sortListByIndex(getPageByFatherId(0, list))
    fatherList.forEach(father => {
        father.children = []
        let childList = sortListByIndex(getPageByFatherId(father.id, list))
        childList.forEach(child => {
            child.path = father.path + child.path
            father.children.push(child)
        })
        routerList.value.push(father)
    })
}

const openTheFather = (father) => {
    let fatherList = sortListByIndex(getPageByFatherId(0, pageList.value))
    fatherList.forEach(fathe => {
        if(father.id === fathe.id){
            fathe.showChild =!fathe.showChild
        }else {
            fathe.showChild = false
        }
    })
}
const openTheChild = (child) => {
    router.push(child.path)

}

init()
</script>

<style scoped>
.father-item {
    width: 200px;
    line-height: 48px;
    padding-left: 24px;
    border-bottom: 1px solid #e4e7ed;
}
.child-item {
    width: 200px;
    line-height: 48px;
    padding-left: 48px;
    border-bottom: 1px solid #e4e7ed;
}
.home-left {
    width: 200px;
    height: 100vh;
    float: left;
    border-right: 1px solid #e4e7ed;

}
.home-right {
    width: calc(100vw - 200px);
    height: 100vh;
    float: left;
}
</style>